package org.xtremeobjects.domain.party;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Transient;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.GenericGenerator;
import org.xtremeobjects.anotations.Hidden;
import org.xtremeobjects.anotations.JavaBean;
import org.xtremeobjects.anotations.Label;
import org.xtremeobjects.anotations.Property;
import org.xtremeobjects.domain.contact.ContactDetail;

import com.google.inject.Inject;

@Entity
@JavaBean
@Label("${self.name}") 
public abstract class Party {

	@Id
	@GeneratedValue(generator = "system-uuid")
	@GenericGenerator(name = "system-uuid", strategy = "uuid")
	@Hidden
	private String id;
	
	public String getId() {
		return this.id;
	}

	@Property(name = "Nome")
	protected String name;
	
	@OneToMany(mappedBy = "party", cascade = CascadeType.ALL, targetEntity = ContactDetail.class)
	@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
	private List<ContactDetail> contactDetails = new ArrayList<ContactDetail>();
	
	public Party( ) {
		this("");
	}
	
	public Party(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String aName) {
		name = aName;
	}

	public List<ContactDetail> getContactDetails() {
		return Collections.unmodifiableList(contactDetails);
	}

	/**
	 * Adds a contact detail to this person.
	 * @param aDescription - Description for this contact detail
	 * @return
	 */
	public ContactDetail addContactDetail(String aDescription) {
		ContactDetail contactDetail = new ContactDetail(this, aDescription);
		contactDetails.add(contactDetail);
		return contactDetail;
	}

	public void removeContactDetail(ContactDetail aContactDetail) {
		contactDetails.remove(aContactDetail);
	}

	public ContactDetail getContactDetail(String description) {
	
		for (ContactDetail contactDetail : contactDetails) {
			if(contactDetail.getDescription().equals(description))
				return contactDetail;
		}
		throw new RuntimeException("Contact detail " + description + " not found" );
	}

	
	public void createNewContactDetail() {
		this.addContactDetail("New contact detail");
	}

	@Inject
	@Transient
	private PartyRepository parties;
	
	public void removeNaoFunciona() {
		parties.remove(this);
	}
}
